import { defineConfig, loadEnv } from 'vite'; // 引入 loadEnv 函数
import vue from '@vitejs/plugin-vue';
import path from 'path';

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd());

  return {
    plugins: [vue()],
    resolve: {
      alias: [
        {
          find: '@',
          replacement: path.resolve(__dirname, 'src'),
        },
      ],
    },
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            // 将 vue 相关的库单独打包
            vue: ['vue', 'vue-router'],
            // 将 lodash 单独打包
            lodash: ['lodash'],
            // 将其他第三方库分组
            // vendor: ['axios', 'moment'],
          },
        },
      },
    },
    server: {
      proxy: {
        [env.VITE_APP_BASE_API]: {
          target: env.VITE_SERVE,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''), // 替换 /api 为空字符串
          bypass: (req, _, proxyOptions) => {
            try {
              // 构造代理 URL
              const proxyUrl = new URL(req.url as string, proxyOptions.target as string).href;
              console.log('Proxy URL:', proxyUrl); // 打印代理后的完整 URL
            } catch (err) {
              console.error('Proxy URL parsing error:', err); // 捕获并打印错误
            }
          },
        },
      },
    },
  };
});